package com.mingqijia.gassafety.job.job.mbp;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.mingqijia.gassafety.db.constant.DtuConstant;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.vo.BatchAppealVO;
import com.mingqijia.gassafety.db.mapper.ConsumerDtuHistoryMapper;
import com.mingqijia.gassafety.db.mapper.DtuMapper;
import com.mingqijia.gassafety.db.mapper.SmartKitchenLogMapper;
import com.mingqijia.gassafety.job.feign.ConsoleSkFeignClient;
import com.mingqijia.gassafety.job.request.ConsumerBindingRequest;
import com.mingqijia.gassafety.job.request.mbp.ConsoleSkUpdateRequest;
import com.mingqijia.gassafety.job.request.mbp.DetailOrderRequest;
import com.mingqijia.gassafety.job.response.ConsoleSkUpdateResponse;
import com.mingqijia.gassafety.job.service.*;
import com.mingqijia.gassafety.job.service.asst.AsstService;
import com.mingqijia.gassafety.job.service.mbp.MbpService;
import com.mingqijia.gassafety.job.service.mbp.TcisService;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.MbpConst;
import com.mingqijia.gassafety.shared.service.ThreeQuotientService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

import static com.mingqijia.gassafety.shared.constant.Constants.APPEAL_STATUS_3;
import static com.mingqijia.gassafety.shared.constant.Constants.IS_DELETED_FALSE;

/**
 * @program: gassafety
 * @description: mbp 工单状态
 * @author: zhang.fei
 * @create: 2022-12-13 13:58
 **/
@Component
@Slf4j
public class MbpStatusUpdateJob {

    @Autowired
    WorkOrderHistoryService workOrderHistoryService;
    @Autowired
    ConsumerService consumerService;
    @Autowired
    TcisService tcisService;
    @Autowired
    MbpWorkOrderService mbpWorkOrderService;
    @Autowired
    AppealLogService appealLogService;
    @Autowired
    SmartKitchenLogMapper smartKitchenLogMapper;
    @Autowired
    ConsoleSkFeignClient client;
    @Autowired
    ConsumerServiceInfoService consumerServiceInfoService;
    @Autowired
    HistoryAlarmService historyAlarmService;
    @Autowired
    HistoryBrokenService historyBrokenService;

    @Autowired
    EquipmentService equipmentService;

    @Autowired
    private ConsumerDtuHistoryMapper consumerDtuHistoryMapper;
    
    @Autowired
    MbpService mbpService;
    
    @Autowired
    AsstService asstService;
    
    @Autowired
    ConsumerLocationService consumerLocationService;

    @Resource
    ThreeQuotientService threeQuotientService;

    @XxlJob("mbpStatusUpdate")
//    @Scheduled(cron = "${gassafety.mbp.job.workOrderStatus}")
    public ReturnT<String> mbpStatusUpdate(String param){
        try {
            XxlJobLogger.log("XXLJOB-mbpStatusUpdate start..." );
            log.info("mbpStatusUpdate ---- start:");
            //查询 工单状态,并更新
            QueryWrapper<WorkOrderHistory> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda() //工单主键
                    .ne(WorkOrderHistory::getOrderType,1) //维修单
                    .eq(WorkOrderHistory::getHandleStatus, 0)  // 进行中
                    .in(WorkOrderHistory::getFromSystem, 0,2)
                    .in(WorkOrderHistory::getWorkSystem, 0,1,2,4)
                    .eq(WorkOrderHistory::getIsDeleted, Constants.IS_DELETED_FALSE);
            List<WorkOrderHistory> list = workOrderHistoryService.list(queryWrapper);
            log.info("mbpStatusUpdate-list:{}",JSONObject.toJSONString(list));
            //遍历未完成工单
            for (WorkOrderHistory history : list) {
                try {
                    String orderNo = history.getOrderNo();
                    if ('S' == orderNo.charAt(orderNo.length() - 1)){
                        orderNo = orderNo.substring(0, orderNo.length() - 1);
                    }
                    Map<String, Object> map = new HashMap<>();
                    JSONArray orderList;
                    Integer code;
                    if (4 == history.getWorkSystem()) {
                        //三商工单
                        Map<String, Object> response = threeQuotientService.queryOrderInfo(history.getOrderNo());
                        orderList = JSONArray.parseArray(JSON.toJSONString(response.get("data")));
                        code = (Integer)response.get("code");
                    } else if (2 == history.getWorkSystem()) {
                        String targetSpId = consumerService.getConsumerRelateSpId(history.getConsumerId(), history.getSpId());
                        Map<String, Object> response =asstService.queryOrderInfo(history.getOrderNo(),targetSpId);
                        orderList = JSONArray.parseArray(JSON.toJSONString(response.get("data")));
                        code = (Integer)response.get("code");
                    } else if( 9 == history.getOrderType() ){
                        map.put("securityPkid",orderNo);
                        log.info("调用安检单详情查询");
                        Map<String, Object> response = mbpService.GetSecurityOrderState(history.getSpId(), map );
                        orderList = JSONArray.parseArray(JSON.toJSONString(response.get("data")));
                        code = (Integer)response.get("code");
                    }else {
                        DetailOrderRequest request = new DetailOrderRequest();
                        request.setUserid(history.getSubsCode());
                        request.setWorkpkid(orderNo);
                        map.put("body", request);
                        log.info("调用1032-工单详情查询");
                        Map<String, Object> response = tcisService.tcisRequest(map, 4, null, history.getSpId(), history.getSubsCode());
                        orderList = JSONArray.parseArray(JSON.toJSONString(response.get("data")));
                        code = (Integer)response.get("code");
                    }
                    if (code.equals(0) && orderList.size()>0){
                        //更新工单状态,
                        for (int i = 0; i < orderList.size(); i++) {
                            JSONObject order = orderList.getJSONObject(i);
                            log.info("mbpStatusUpdate-order:{}",JSONObject.toJSONString(order));
                            //工单完成
                            if (MbpConst.WORK_STATE_END.equals(order.getString("state"))&&
                                    !StringUtils.isEmpty(history.getNewDeviceId())) {
                                QueryWrapper<Consumer> consumerWrapper = new QueryWrapper<>();
                                consumerWrapper.lambda().or().eq(Consumer::getSubsCode, history.getSubsCode())
                                        .eq(Consumer::getIsDeleted, IS_DELETED_FALSE)
                                        .eq(Consumer::getSpId, history.getSpId());
                                List<Consumer> consumers = consumerService.list(consumerWrapper);
                                log.info("mbpStatusUpdate-consumers:{}",JSONObject.toJSONString(consumers));
                                if (!CollectionUtils.isEmpty(consumers)){
                                    Consumer consumer = consumers.get(0);
                                    LambdaUpdateWrapper<Dtu> old = new LambdaUpdateWrapper<>();
                                    
                                    // update by wangwei for 11402
                                    if(org.apache.commons.lang.StringUtils.isNotEmpty(history.getDeviceId()) && 
                                        history.getDeviceId().length() >= DtuConstant.IMEI_MIN_LENGTH) {
                                        String deviceId = history.getDeviceId();
                                        if (deviceId.contains("-")) {
                                            String[] imeis = deviceId.split("-");
                                            deviceId = imeis[0];
                                        }
                                        old.eq(Dtu::getParentImei, deviceId)
                                                .eq(Dtu::getIsDeleted, IS_DELETED_FALSE)
                                                .set(Dtu::getConsumerId, consumer.getId())
                                                .set(Dtu::getSectorType, StringUtils.isEmpty(consumer.getIndustryType()) ? Constants.BLANK : consumer.getIndustryType());
                                        equipmentService.update(old);
                                    } else {
                                        log.warn("工单:{} 不符合规则无法更新", JSONObject.toJSONString(history));
                                    }
                                    
                                    ConsumerBindingRequest oldRequest = new ConsumerBindingRequest();
                                    oldRequest.setImei(history.getDeviceId());
                                    oldRequest.setConsumerId(consumer.getId());
                                    oldRequest.setSpId(consumer.getSpId());
                                    oldRequest.setOutOrderCode(history.getPkid());
                                    oldRequest.setEvent(1);
                                    String newDeviceId = history.getNewDeviceId();
                                    if (newDeviceId.contains("-")) {
                                        String[] imeis = newDeviceId.split("-");
                                        newDeviceId = imeis[0];
                                    }
                                    LambdaUpdateWrapper<Dtu> lqw = new LambdaUpdateWrapper<>();
                                    lqw.eq(Dtu::getParentImei,newDeviceId)
                                            .eq(Dtu::getIsDeleted, IS_DELETED_FALSE)
                                            .set(Dtu::getConsumerId, 0)
                                            .set(Dtu::getSectorType, Constants.BLANK)
                                            .set(Dtu::getInstallationPosition,null)
                                            .set(Dtu::getInstallationAddress,null)
                                            .set(Dtu::getPositionLat,0.0)
                                            .set(Dtu::getPositionLon,0.0)
                                            .set(Dtu::getSource,0);
                                    equipmentService.update(lqw);
                                    ConsumerBindingRequest newRequest = new ConsumerBindingRequest();
                                    newRequest.setImei(history.getNewDeviceId());
                                    newRequest.setConsumerId(consumer.getId());
                                    newRequest.setSpId(consumer.getSpId());
                                    newRequest.setOutOrderCode(history.getPkid());
                                    newRequest.setEvent(0);
                                    saveConsumerDtu(oldRequest, newRequest.getImei(), consumer.getIndustryType());
                                    saveConsumerDtu(newRequest, "", "");
                                    consumerLocationService.updateConsumerLocationDeviceNum(consumer.getSpId(),consumer.getId());
                                }
                            }
                            if (MbpConst.WORK_STATE_FINISH.equals(order.getString("state"))
                                    ||MbpConst.WORK_STATE_END.equals(order.getString("state"))){
                                if (history.getWorkSystem() == 2 && history.getConsumerId() > 0) {
                                    LambdaUpdateWrapper<Consumer> consumerWrapper = new LambdaUpdateWrapper<>();
                                    consumerWrapper.or().eq(Consumer::getId, history.getConsumerId())
                                            .set(Consumer::getStatus, 0);
                                    consumerService.update(consumerWrapper);
                                } else {
                                    consumerService.updateStatusByCode(history.getSubsCode());
                                }

                                //更新工单状态
                                WorkOrderHistory workOrderHistory = new WorkOrderHistory();
                                workOrderHistory.setId(history.getId());
                                workOrderHistory.setHandleStatus(1);
                                workOrderHistory.setCompleteTime(order.getDate("finishtime"));
                                workOrderHistoryService.updateById(workOrderHistory);
                                if (!StringUtils.isEmpty(history.getNewDeviceId())){
                                    String format = DateUtil.format(workOrderHistory.getCompleteTime(), "yyyy-MM-dd");
                                    String newDeviceId = history.getNewDeviceId();
                                    if (newDeviceId.contains("-")) {
                                        String[] imeis = newDeviceId.split("-");
                                        newDeviceId = imeis[0];
                                    }
                                    LambdaUpdateWrapper<Dtu> lqw = new LambdaUpdateWrapper<>();
                                    lqw.eq(Dtu::getParentImei, newDeviceId)
                                            .eq(Dtu::getIsDeleted, IS_DELETED_FALSE)
                                            .set(Dtu::getInstallDate, format);
                                    equipmentService.update(lqw);
                                    LambdaUpdateWrapper<ConsumerServiceInfo> serviceInfoLqw = new LambdaUpdateWrapper<>();
                                    serviceInfoLqw.eq(ConsumerServiceInfo::getImei,history.getNewDeviceId())
                                        .eq(ConsumerServiceInfo::getIsDeleted, IS_DELETED_FALSE)
                                        .set(ConsumerServiceInfo::getRemark, new StringBuilder().append("设备号：").append(history.getNewDeviceId())
                                            .append("安装日期：").append(format).append("当前状态：关联").toString());
                                    consumerServiceInfoService.update(serviceInfoLqw);
                                }
                                LambdaUpdateWrapper<AppealLog> selectWrapper = new LambdaUpdateWrapper<>();
                                selectWrapper.eq(AppealLog::getWorkorderId,history.getId()).eq(AppealLog::getIsDeleted,0);
                                List<AppealLog> appealLogList = appealLogService.list(selectWrapper);
                                //更新诉求表状态
                                LambdaUpdateWrapper<AppealLog> updateWrapper = new LambdaUpdateWrapper<>();
                                updateWrapper.eq(AppealLog::getWorkorderId,history.getId()).eq(AppealLog::getIsDeleted,0);
                                AppealLog alarmApplyLog = new AppealLog();
                                alarmApplyLog.setAppealStatus(APPEAL_STATUS_3);
                                alarmApplyLog.setAppealResult("完成");
                                appealLogService.update(alarmApplyLog,updateWrapper);
                                if (!CollectionUtils.isEmpty(appealLogList)) {
                                    alarmApplyLog.setAppealType(appealLogList.get(0).getAppealType());
                                }
                                log.info("mbp工单处理完成，更新报警器设备报警诉求记录："+alarmApplyLog.toString());
                                // 更新报警/故障信息记录主表
                                if (alarmApplyLog.getAppealType() != null && alarmApplyLog.getAppealType() == 0) {
                                    LambdaUpdateWrapper<HistoryAlarm> historyAlarmWrapper = new LambdaUpdateWrapper<>();
                                    historyAlarmWrapper.eq(HistoryAlarm::getWorkorderId,history.getId()).eq(HistoryAlarm::getIsDeleted,0);
                                    HistoryAlarm historyAlarm = new HistoryAlarm();
                                    historyAlarm.setAppealStatus(alarmApplyLog.getAppealStatus());
                                    historyAlarm.setAppealResult(alarmApplyLog.getAppealResult());
                                    boolean historyAlarmResult = historyAlarmService.update(historyAlarm,historyAlarmWrapper);
                                    log.info("工单处理完成，更新报警器设备报警记录,结果：{}，内容：{}",historyAlarmResult,historyAlarm.toString());
                                } else  if (alarmApplyLog.getAppealType() != null && alarmApplyLog.getAppealType() == 1) {
                                    LambdaUpdateWrapper<HistoryBroken> historyBrokenWrapper = new LambdaUpdateWrapper<>();
                                    historyBrokenWrapper.eq(HistoryBroken::getWorkorderId,history.getId()).eq(HistoryBroken::getIsDeleted,0);
                                    HistoryBroken historyBroken = new HistoryBroken();
                                    historyBroken.setAppealStatus(alarmApplyLog.getAppealStatus());
                                    historyBroken.setAppealResult(alarmApplyLog.getAppealResult());
                                    boolean historyBrokenResult = historyBrokenService.update(historyBroken,historyBrokenWrapper);
                                    log.info("工单处理完成，更新报警器设备故障记录,结果：{}，内容：{}",historyBrokenResult,historyBroken.toString());
                                }

                                LambdaUpdateWrapper<SmartKitchenLog> queryWrapper2 = new LambdaUpdateWrapper<>();
                                queryWrapper2.eq(SmartKitchenLog::getWorkorderId,history.getId()).eq(SmartKitchenLog::getIsDeleted,0);
                                List<SmartKitchenLog> smartKitchenLogs = smartKitchenLogMapper.selectList(queryWrapper2);
                                if (CollectionUtil.isEmpty(smartKitchenLogs)) {
                                    return ReturnT.SUCCESS;
                                }
                                SmartKitchenLog smartKitchenLog = smartKitchenLogs.get(0);
                                if (smartKitchenLog != null) {
                                    LambdaUpdateWrapper<SmartKitchenLog> updateWrapper2 = new LambdaUpdateWrapper<>();
                                    updateWrapper2.eq(SmartKitchenLog::getWorkorderId,history.getId()).eq(SmartKitchenLog::getIsDeleted,0);
                                    SmartKitchenLog insertLog = new SmartKitchenLog();
                                    insertLog.setId(smartKitchenLog.getId());
                                    insertLog.setAppealStatus(APPEAL_STATUS_3);
                                    insertLog.setAppealResult("完成");
                                    insertLog.setUpdatedAt(new Date());
                                    int flag = smartKitchenLogMapper.updateById(insertLog);
                                    log.info("工单处理完成，更新智慧厨房诉求记录表,结果：{}，内容：{}：", flag == 1, insertLog.toString());
                                    if (flag == 1){
                                        ConsoleSkUpdateRequest consoleSkUpdateRequest = new ConsoleSkUpdateRequest();
                                        consoleSkUpdateRequest.setId(smartKitchenLog.getRecordId());
                                        consoleSkUpdateRequest.setDealStatus(3);
                                        consoleSkUpdateRequest.setResult("完成");
                                        log.info("alarmSOSUpdate-request:{}",JSONObject.toJSONString(consoleSkUpdateRequest));
                                        ConsoleSkUpdateResponse consoleSkUpdateResponse = client.alarmSOSUpdate(consoleSkUpdateRequest);
                                        log.info("alarmSOSUpdate-consoleSkUpdateResponse:{}",JSONObject.toJSONString(consoleSkUpdateResponse));
                                    }
                                }
                            }


                        }
                    }else {
                        log.info("工单:{} 查询1032失败或未查询到工单",history.getOrderNo());
                    }
                } catch (Exception e) {
                    log.info("查询工单详情时报错{}, 工单{}:", e.getMessage(), history);
                }
            }

        }catch (Exception e){
            log.info("workOrderStatus-error:{}", e);
        }
        XxlJobLogger.log("XXLJOB-mbpStatusUpdate end..." );

        return ReturnT.SUCCESS;
    }


    public void saveConsumerDtu( ConsumerBindingRequest request, String oldImei, String industryType) {
        log.info("MbpStatusUpdateJob-saveConsumerDtu-request:{}",JSONObject.toJSONString(request));
        //绑定记录新增
        ConsumerDtuHistory history = new ConsumerDtuHistory();
        history.setId(null);
        history.setBindChannel(Constants.BIND_CHANNEL_MBP);
        history.setOutOrderCode(request.getOutOrderCode());
        history.setDeviceId(request.getImei());
        history.setEvent(request.getEvent());
        history.setIMEI(request.getImei());
        history.setConsumerId(request.getConsumerId());
        history.setOperationPersonCode("时刻助手销售单");
        history.setOperationPersonName("asst");
        history.setRemark(Constants.STR_EMPTY);
        history.setSpId(request.getSpId());
        consumerDtuHistoryMapper.insert(history);
        if (request.getEvent() == 0) {
            consumerServiceInfoService.deleteConsumerServiceInfo(request.getImei());
        } else if (request.getEvent() == 1) {
            consumerServiceInfoService.addConsumerServiceInfo(request.getImei(), oldImei, industryType);
        }
    }

}
